#include <vector>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/regex.hpp>
#include <iostream>
#include "database/Client.hpp"
#include "TCPServer.h"
#include "IntegrityDatas.h"
#include "Protocol.h"
#include "Config.h"

void CSProtocol::Register::receiveTreat(TCPConnection &connexion, IData *udata)
{
  CSProtocol::Register *data = static_cast<CSProtocol::Register*>(udata);
  if (!data)
    return;
  CSProtocol::Header header = CSProtocol::Header();
  header.spontaneous = false;
  IData *pcmd;
  std::cout<< data->login << std::endl;
  if (IntegrityDatas::checkLogin(data->login)
      && IntegrityDatas::checkPass(data->pass)
      && !((connexion.getServer())->getDB()).clientExist(data->login))
    {
      std::string slogin = std::string(data->login);
      std::string spass = std::string(data->pass);
      std::string smail = std::string(data->email);
      this->registerNewUser(slogin, spass, smail, (connexion.getServer())->getDB());
      header.code = CSProtocol::Ok::code;
      CSProtocol::Ok command = CSProtocol::Ok();
      header.dataLength = sizeof(CSProtocol::Ok);
      pcmd = &command;
      strcpy(command.what, "Register succesfull.");
    }
  else
    {
      header.code = CSProtocol::Ko::code;
      CSProtocol::Ko command = CSProtocol::Ko();
      if (((connexion.getServer())->getDB()).clientExist(data->login))
	strcpy(command.what, "Register failed, login already exist.");
      else
	strcpy(command.what, "Register failed, only alphanumeric char are allowed.");
      header.dataLength = sizeof(CSProtocol::Ko);
      pcmd = &command;
    }
  connexion.write(header, *pcmd);
}

void CSProtocol::Register::sendTreat(TCPConnection &connexion)
{
}

Client *CSProtocol::Register::registerNewUser(std::string &login, std::string &pass,
					      std::string &email, DatabaseManager &db)
{
  Client *clt = new Client();
  clt->setLogin(login);
  clt->setPassword(pass);
  clt->setMail(email);
  db.addClient(clt);
  try
    {
      clt->save(PATH_DATAS + clt->getLogin() + ".txt");
    }
  catch (std::exception &e)
    {
      std::cerr << "Cannot register new client " << e.what() << std::endl;
    }
}
